# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
 -------------------------------------------------
    File Name:     postman.py.py
    Description:   封装 pm 类功能（环境变量、响应管理等）
 -------------------------------------------------
1. 环境变量管理：可以设置、获取、删除环境变量。
2. 临时变量管理：可以设置、获取、删除临时变量。
3. 响应对象管理：可以在后置脚本中访问响应对象 (pm.response 类似的功能)。
 """
import re

from jsonpath import jsonpath
from hellchin_lib import PostManAssertMethod

from core.variable_management import Environment, Variables, Globals
from core.caselog import CaseRunLog

# environment
environment = Environment()


# 定义一个特殊对象
# class Undefined:
#     def __repr__(self):
#         return "Undefined"
#
#
# # 实例化一个特殊对象
# UNDEFINED = Undefined()

class BaseMethod(CaseRunLog):

    def json_extract(self, response_obj, path):
        """jsonpath数据提取"""
        self.info_log('------------- jsonpath提取数据 ------------')
        value = jsonpath(response_obj, path)
        result_value = value[0] if len(value) == 1 else value
        self.info_log("数据源: {}".format(response_obj))
        self.info_log("提取路径: {}".format(path))
        self.info_log("提取结果: {}".format(result_value))
        return result_value

    def re_extract(self, response_obj, pattern):
        """正则表达式提取"""
        self.info_log("------------- 正则表达式提取数据 ------------")
        self.info_log("数据源: {}".format(response_obj))
        if not isinstance(response_obj, str):
            response_obj = str(response_obj)
        value = re.search(pattern, response_obj)
        value = value.group(1) if value else None
        self.info_log("提取模式: {}".format(pattern))
        self.info_log("提取结果: {}".format(value))
        return value


class BasePM(PostManAssertMethod, BaseMethod):
    """封装 Postman 风格的功能"""

    def __init__(self):
        super().__init__()
        # 创建全局环境对象，环境变量在此管理
        self._environment = environment
        self._variables = Variables()
        self._globals = Globals()

    @property
    def globals(self):
        """管理全局变量"""
        return self._globals

    @property
    def environment(self):
        """管理环境变量"""
        return self._environment

    @property
    def variables(self):
        """管理临时变量: 访问所有有效的变量"""
        return self._variables


class PrePM(BasePM):
    """前置操作的PM"""

    def __init__(self, context=None):
        super().__init__()

    def request(self, method, url, **kwargs):
        pass


class PostPM(BasePM):
    """后置操作的PM"""

    def __init__(self, context=None):
        super().__init__()
        self._response = dict()  # 响应对象

    # @property
    # def response(self):
    #     """获取响应"""
    #
    #     class ResponseProxy:
    #         def __init__(self, response):
    #             self._response = response
    #
    #         def json(self):
    #             print(f"response_type: ", type(self._response))
    #             return Box(
    #                 self._response.json(),
    #                 default_box=True,  # 是否在访问不存在的键时返回空的 Box 对象
    #                 default_box_attr=UNDEFINED,  # 不存在的键返回默认值 undefined
    #             )
    #
    #         def __getattr__(self, item):
    #             # 代理其他属性和方法到原始 response 对象
    #             return getattr(self._response, item)
    #
    #     return ResponseProxy(self._response)
    #
    # @response.setter
    # def response(self, value):
    #     """设置响应"""
    #     self._response = value


if __name__ == '__main__':
    pass
